-- Equipped Item Level
-- author: villiv (some rewrited by me)

local module = {}
module.name = "Equipped Item Level"
module.Init = function()
    if not SCDB.modules[module.name] then return end
	if SCDB[module.name] == nil then SCDB[module.name] = {} end
	if SCDB[module.name]["Max ItemLevel"] == nil then SCDB[module.name]["Max ItemLevel"] = 0 end

    local PREFIX = STAT_FORMAT:format(STAT_AVERAGE_ITEM_LEVEL)
    local UPDATED = '*'
    local RETRIEVING = GRAY_FONT_COLOR_CODE .. RETRIEVING_DATA .. CONTINUED
    local UNAVAILABLE = GRAY_FONT_COLOR_CODE .. UNAVAILABLE

    local handler = CreateFrame('Frame')
    handler:Hide()

    local isInspecting
    
    local function GetTooltipPlayerUnit(tooltip)
        local _, unit = tooltip:GetUnit()
        if not unit then
            local mouseFocus = GetMouseFocus()
            unit = mouseFocus and mouseFocus.unit
            if not unit then return end
        end
        return UnitIsPlayer(unit) and unit
    end

    local function SetTooltipItemLevel(tooltip, itemLevel, percent)
        tooltip:AddLine(PREFIX.." "..itemLevel..", " .. percent .. "%")
        tooltip:Show()
    end

    local function UnitItemLevel (unit)
        local total, count = 0, 0
        local isRetrieving, is2Handed

        for i = INVSLOT_FIRST_EQUIPPED, INVSLOT_LAST_EQUIPPED do
            if i ~= INVSLOT_BODY and i ~= INVSLOT_TABARD then
                local id = GetInventoryItemID(unit, i)
                local _, level, equipLoc

                if id then
                    _, _, _, level, _, _, _, _, equipLoc = GetItemInfo(id)
                    isRetrieving = isRetrieving or not (level and equipLoc)
                end

                if not isRetrieving then
                    total, count = total + (level or 0), count + 1

                    if i == INVSLOT_MAINHAND then
                        is2Handed = not id and 0 or equipLoc == 'INVTYPE_2HWEAPON' and 1
                    elseif i == INVSLOT_OFFHAND then
                        is2Handed = is2Handed == 0 and equipLoc == 'INVTYPE_2HWEAPON' or is2Handed == 1 and not id
                    end
                end
            end
        end

        local il = math.floor(total / (is2Handed and count - 1 or count))
        if not isRetrieving then 
            if il > SCDB[module.name]["Max ItemLevel"] then SCDB[module.name]["Max ItemLevel"] = il end
            return il
        end
    end

    local function UpdateItemLevel(unit)
        if not InCombatLockdown() and UnitIsPlayer(unit) then
            local itemLevel
            local guid = UnitGUID(unit)
            local percent = 0

            if unit == 'player' then
                itemLevel = UnitItemLevel(unit)
                percent = math.floor(itemLevel / (SCDB[module.name]["Max ItemLevel"] / 100))
                itemLevel = itemLevel .. UPDATED
            elseif CanInspect(unit) and not (InspectFrame and InspectFrame:IsShown()) then
                if  not isInspecting then
                    NotifyInspect(unit)
                    handler:RegisterEvent('UNIT_INVENTORY_CHANGED')
                    isInspecting = true
                end

                itemLevel = UnitItemLevel(unit)
                if itemLevel then
                    percent = math.floor(itemLevel / (SCDB[module.name]["Max ItemLevel"] / 100))
                    itemLevel = itemLevel .. UPDATED
                else
                    handler:Show()
                    itemLevel = RETRIEVING
                end
            else
                itemLevel = UNAVAILABLE
            end
            
            if itemLevel then return SetTooltipItemLevel(GameTooltip, itemLevel, percent) end
        end
    end

    GameTooltip:HookScript('OnTooltipSetUnit', function (self)
        local unit = GetTooltipPlayerUnit(self)
        if not unit then return end
        return UpdateItemLevel(unit)
    end)

    GameTooltip:HookScript('OnTooltipCleared', function (self)
        if isInspecting then
            ClearInspectPlayer()
            handler:UnregisterEvent('UNIT_INVENTORY_CHANGED')
            isInspecting = nil
        end
    end)

    local updateTooltip = TOOLTIP_UPDATE_TIME

    handler:SetScript('OnUpdate', function (self, elapsed)
        updateTooltip = updateTooltip - elapsed
        if updateTooltip > 0 then return end

        self:Hide()
        updateTooltip = TOOLTIP_UPDATE_TIME

        local unit = GetTooltipPlayerUnit(GameTooltip)
        if not unit then return end
        return UpdateItemLevel(unit)
    end)

    handler:SetScript('OnEvent', function (self, event, arg1)
        local unit = GetTooltipPlayerUnit(GameTooltip)
        if not unit then return end
        return UpdateItemLevel(unit)
    end)

end
tinsert(SuperClassic.modules, module) -- finish him!